package top.yokey.android.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

import com.bumptech.glide.Glide;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.yokey.android.R;
import top.yokey.android.base.App;
import top.yokey.android.base.BaseActivity;
import top.yokey.android.base.GlideEngine;
import top.yokey.android.fragment.NotificationsFragment;
import top.yokey.android.http.BaseCallBack;
import top.yokey.android.http.HttpHelp;

public class DynamicAddActivity extends BaseActivity {

    private AppCompatTextView sendTextView;
    private AppCompatEditText contentEditText;
    private AppCompatImageView[] mainImageView = new AppCompatImageView[9];

    private List<LocalMedia> imageList = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_dynamic_add);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {

        sendTextView = findViewById(R.id.sendTextView);
        contentEditText = findViewById(R.id.contentEditText);
        mainImageView[0] = findViewById(R.id.main1ImageView);
        mainImageView[1] = findViewById(R.id.main2ImageView);
        mainImageView[2] = findViewById(R.id.main3ImageView);
        mainImageView[3] = findViewById(R.id.main4ImageView);
        mainImageView[4] = findViewById(R.id.main5ImageView);
        mainImageView[5] = findViewById(R.id.main6ImageView);
        mainImageView[6] = findViewById(R.id.main7ImageView);
        mainImageView[7] = findViewById(R.id.main8ImageView);
        mainImageView[8] = findViewById(R.id.main9ImageView);

    }

    @Override
    public void initEvent() {

        for (int i = 0; i < mainImageView.length; i++) {
            final int pos = i;
            mainImageView[i].setOnClickListener(view -> {
                //如果已经存在图片，弹框询问用户操作。
                if (imageList.size() != 0 && pos < imageList.size() && imageList.get(pos) != null) {
                    new AlertDialog.Builder(this)
                            .setIcon(R.mipmap.ic_avatar)
                            .setTitle("确认您的选择")
                            .setMessage("图片操作")
                            .setCancelable(false)
                            .setPositiveButton("删除", (dialogInterface, m) -> {
                                imageList.remove(pos);
                                handlerImage();
                            })
                            .setNegativeButton("更换", (dialogInterface, m) -> {
                                PictureSelector.create(this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .loadImageEngine(GlideEngine.createGlideEngine())
                                        .maxSelectNum(1)
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(List<LocalMedia> result) {
                                                boolean have = false;
                                                for (int k = 0; k < imageList.size(); k++) {
                                                    if (result.get(0).getPath().equals(imageList.get(k).getPath())) {
                                                        have = true;
                                                        break;
                                                    }
                                                }
                                                if (have) {
                                                    Toast.makeText(DynamicAddActivity.this, "重复图片不会被添加", Toast.LENGTH_SHORT).show();
                                                } else {
                                                    imageList.remove(pos);
                                                    imageList.add(pos, result.get(0));
                                                    handlerImage();
                                                }
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                            })
                            .show();
                    return;
                }
                // pos 为 0 imageList大小为0的时候 允许第一个imageview响应点击事件，其他不允许
                if (pos != imageList.size()) {
                    return;
                }
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .maxSelectNum(9 - imageList.size())
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(List<LocalMedia> result) {
                                //两个问题需要解决：图片去重，图片数量超限
                                boolean isTips = false;
                                for (int j = 0; j < result.size(); j++) {
                                    boolean have = false;
                                    for (int k = 0; k < imageList.size(); k++) {
                                        if (result.get(j).getPath().equals(imageList.get(k).getPath())) {
                                            isTips = true;
                                            have = true;
                                            break;
                                        }
                                    }
                                    if (!have) imageList.add(result.get(j));
                                }
                                if (isTips) {
                                    Toast.makeText(DynamicAddActivity.this, "重复图片不会被添加", Toast.LENGTH_SHORT).show();
                                }
                                handlerImage();
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            });
        }

        sendTextView.setOnClickListener(view -> {
            String content = contentEditText.getText().toString();
            if (content.isEmpty()) {
                Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
                return;
            }
            sendTextView.setEnabled(false);
            sendTextView.setText("发表中...");
            HttpHelp.get().ready("circle", "add")
                    .add("content", content)
                    .get(new BaseCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            if (imageList.size() != 0) {
                                uploadImage(data);
                            } else {
                                Toast.makeText(DynamicAddActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        }

                        @Override
                        public void onError(String reason) {
                            Toast.makeText(DynamicAddActivity.this, reason, Toast.LENGTH_SHORT).show();
                            sendTextView.setEnabled(true);
                            sendTextView.setText("发表");
                        }
                    });
        });

    }

    //处理选择后的图片
    private void handlerImage() {

        System.out.println(imageList.size());
        //将所有imageview的默认图片设置为空白
        for (AppCompatImageView appCompatImageView : mainImageView) {
            appCompatImageView.setImageResource(R.mipmap.ic_add_image_null);
        }
        //根据imagelist的大小加载对应的图片
        for (int i = 0; i < imageList.size(); i++) {
            Glide.with(this).load(imageList.get(i).getPath()).into(mainImageView[i]);
        }
        //如果不够9张，为下一个imageview设置添加图片
        if (imageList.size() < 9) {
            mainImageView[imageList.size()].setImageResource(R.mipmap.ic_add_image);
        }

    }

    private void uploadImage(String id) {

        //上传完成的标识
        if (imageList.size() == 0) {
            Toast.makeText(DynamicAddActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        HttpHelp.get().ready("circle", "uploadImage").add("id", id).post(new File(imageList.get(0).getPath()), new BaseCallBack() {
            @Override
            public void onSuccess(String data) {
                imageList.remove(0);
                uploadImage(id);
            }

            @Override
            public void onError(String reason) {
                Toast.makeText(DynamicAddActivity.this, reason, Toast.LENGTH_SHORT).show();
            }
        });

    }

}
